// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#include <fmt/format.h>
#include <melon/init/init.h>
#include <turbo/flags/flag.h>
#include <turbo/log/logging.h>
#include <gtest/gtest.h>
#include <pollux/common/base/fs.h>
#include <pollux/testing/exec/aggregation_fuzzer_runner.h>
#include <pollux/testing/exec/duck_query_runner.h>
#include <pollux/functions/prestosql/aggregates/register_aggregate_functions.h>
#include <pollux/functions/prestosql/registration/registration_functions.h>

using namespace kumo::pollux;

TURBO_FLAG(std::string,
    aggregation_fuzzer_repro_path,
    "",
    "Directory path where all plans generated by AggregationFuzzer are "
    "expected to reside. Any plan paths "
    "already specified via a startup flag will take precedence.");

TURBO_FLAG(std::string,
    plan_nodes_path,
    "",
    "Path for plan nodes to be restored from disk. This will enable single run "
    "of the fuzzer with the on-disk persisted plan information.");

TURBO_FLAG(std::string,
    presto_url,
    "",
    "Presto coordinator URI along with port. If set, we use Presto "
    "source of truth. Otherwise, use DuckDB. Example: "
    "--presto_url=http://127.0.0.1:8080");

TURBO_FLAG(uint32_t,
    req_timeout_ms,
    3000,
    "Timeout in milliseconds for HTTP requests made to reference DB, "
    "such as Presto. Example: --req_timeout_ms=2000");

static std::string checkAndReturnFilePath(
    const std::string_view& fileName,
    const std::string& flagName) {
  auto path =
      fmt::format("{}/{}", FLAGS_aggregation_fuzzer_repro_path, fileName);
  if (fs::exists(path)) {
    KLOG(INFO) << "Using " << flagName << " = " << path;
    return path;
  } else {
    KLOG(INFO) << "File for " << flagName << " not found.";
  }
  return "";
}

static void checkDirForExpectedFiles() {
  KLOG(INFO) << "Searching input directory for expected files at "
            << FLAGS_aggregation_fuzzer_repro_path;

  FLAGS_plan_nodes_path = FLAGS_plan_nodes_path.empty()
      ? checkAndReturnFilePath(exec::test::kPlanNodeFileName, "plan_nodes")
      : FLAGS_plan_nodes_path;
}

int main(int argc, char** argv) {
  ::testing::InitGoogleTest(&argc, argv);

  melon::Init init(&argc, &argv);
  kumo::pollux::memory::MemoryManager::initialize({});

  if (!FLAGS_aggregation_fuzzer_repro_path.empty()) {
    checkDirForExpectedFiles();
  }

  kumo::pollux::aggregate::prestosql::registerAllAggregateFunctions();
  kumo::pollux::functions::prestosql::registerAllScalarFunctions();

  std::shared_ptr<memory::MemoryPool> rootPool{
      memory::memoryManager()->addRootPool()};
  auto queryRunner = kumo::pollux::exec::test::setupReferenceQueryRunner(
      rootPool.get(),
      FLAGS_presto_url,
      "aggregation_fuzzer",
      FLAGS_req_timeout_ms);
  return exec::test::AggregationFuzzerRunner::runRepro(
      FLAGS_plan_nodes_path, std::move(queryRunner));
}
